# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render_to_response, redirect
from django.contrib.auth import authenticate, login, logout


def display_login(request):
    return render_to_response('logon.html', {'show_menu': False, 'show_submenu': False})

def auth_login(request):
    try:
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
    except KeyError:
        return display_login(request)

    if user is not None:
        if user.is_active:
            login(request, user)
            original_url = request.POST['originalURL']
            if (original_url is not None and original_url != ''):
                return redirect(original_url)
            else:
                return pyfacture(request)
        else:
            return render_to_response('logon.html', {'show_menu': False, 'show_submenu': False, 'error_msg': 'User is not active'})
    else:
        return render_to_response('logon.html', {'show_menu': False, 'show_submenu': False, 'error_msg': 'Invalid username/password'})

def auth_logout(request):
    logout(request)
    return display_login(request)

def pyfacture(request):
    if not request.user.is_authenticated():
        return display_login(request)

    return render_to_response('base.html', {'show_menu': True, 'show_submenu': False})
